<template>
  <VPage>
    <VTable ref="tableRef" v-bind="tableOptions">
      <template #form="{ form }">
        <VGroup>
          <el-select v-model="form.input.type" style="width: 130px">
            <el-option label="头程备库单号" value="deliver_no"></el-option>
            <el-option label="采购单号" value="purchase_no"></el-option>
          </el-select>
          <el-input v-model="form.input.value" placeholder="请输入" class="w-40"></el-input>
        </VGroup>
        <VGroup>
          <el-select v-model="form.skuInfo.type" class="w-28">
            <el-option label="sku" value="sku"></el-option>
            <el-option label="赛盒SKU" value="sai_he_sku"></el-option>
            <el-option label="自定义sku" value="custom_sku"></el-option>
          </el-select>
          <el-input v-model="form.skuInfo.value" placeholder="请输入" class="w-40"></el-input>
        </VGroup>
        <VSelect v-model="form.supplier_name" placeholder="供应商" type="supplierName" allow-create style="min-width: 200px" multiple
          collapse-tags clearable filterable />
        <VSelect v-model="form.order_source" placeholder="头程备库类型" :options="options.order_source || []" multiple
          collapse-tags filterable clearable style="min-width: 160px" />
        <VSelect v-model="form.destination_warehouse" placeholder="目的仓库" type="warehouse156" multiple collapse-tags
          filterable clearable style="min-width: 160px" />
        <VSelect v-model="form.purchase_type" placeholder="供应商类型" :options="options.purchase_type || []" multiple
          collapse-tags filterable clearable style="min-width: 160px" />
        <!-- <VSelect v-model="form.settlement_type" placeholder="结算方式" :options="options.settlement_type || []" multiple
          collapse-tags filterable clearable style="min-width: 160px" /> -->
        <VCascader v-model="form.purchase_user_id" placeholder="采购人员" multiple collapse-tags filterable clearable
          style="min-width: 160px" />
        <VSelect v-model="form.receipt_status" placeholder="状态" :options="options.receipt_status || []" multiple
          collapse-tags filterable clearable style="min-width: 160px" />
        <VSelect v-model="form.is_download" placeholder="是否下载" :options="options.is_download || []" multiple collapse-tags
          filterable clearable style="min-width: 160px" />
        <VSelect v-model="form.pickup_type" placeholder="提货类型" :options="options.pickup_type || []" multiple collapse-tags
          filterable clearable style="min-width: 160px" />
        <VGroup>
          <el-select v-model="form.dateRange.type" style="width: 130px">
            <el-option label="外验完成时间" value="except_deliver_time"></el-option>
            <el-option label="预计出库时间" value="inspection_time"></el-option>
          </el-select>
          <VDate v-model="form.dateRange.value" />
        </VGroup>
      </template>
      <template #toolbar_btns>
        <VButton auth="/purchase/manage/warehouse/download" :loading="loadings.download" @click="handleBatch('download')">批量下载入仓文件</VButton>
        <VButton auth="/purchase/manage/warehouse/uploadReceipt" @click="handleBatch('upload')">上传入仓文件</VButton>
        <VExport auth="/purchase/manage/warehouse/export" mainKey="wr_id" name="warehouse-receipt" :tableRef="tableRef" task class="ml-auto" />
      </template>
    </VTable>
    <Add ref="addRef" :options="options" @success="query"/>
    <Upload ref="uploadRef" :options="options" @success="query" />
    <UploadReceipt ref="uploadReceiptRef" :options="options" @success="query" />
    <Change ref="changeRef" :options="options" @success="query" />
    <VLog ref="logRef" />
    <BoxDetail ref="boxDetailRef" />
  </VPage>
</template>
  
<script setup lang="jsx" name="Account">
import api from './api'
import Add from './components/Add'
import Upload from './components/Upload'
import UploadReceipt from './components/UploadReceipt'
import Change from './components/Change'
import BoxDetail from './components/BoxDetail'


import { getOption } from '@/api/public'
import { ElMessage, ElMessageBox } from 'element-plus'
import { download } from '@/utils'

const baseName = 'warehouse_receipt'
const tableRef = ref()
const historeRef = ref()
const loadings = reactive({})
// 查询
const query = () => {
  tableRef?.value.query()
}

// 添加
const addRef = ref()

// 获取options
const options = ref({})
Promise.all([
  getOption({ type: baseName }).then(res => res.data),
  getOption({ type: 'purchase' }).then(res => res.data),
  Promise.resolve({ test: [{ label: '没有数据', value: 1 }] })
]).then(res => {
  options.value = res.reduce((acc, cur) => (((acc = { ...acc, ...cur }), acc)), {})
})

// 批量操作
const uploadReceiptRef = ref()
const handleBatch = (name) => {
  const selection = tableRef.value.$table.getCheckboxRecords()
  if (!selection.length) {
    ElMessage.warning('请先选择行')
    return
  }
  const wr_ids = selection.map(d => d.wr_id)
  const showLoading = () => loadings[name] = true
  const closeLoading = () => loadings[name] = false
  const handle = {
    download: async () => {
      showLoading()
      const res = await api.download({wr_ids})
      await download([res.data.url])
      closeLoading()
    },
    upload: () => {
      uploadReceiptRef?.value.open(wr_ids)
    }
  }
  handle[name]()
}

// 单行操作
const logRef = ref()
const uploadRef = ref()
const changeRef = ref()
const boxDetailRef = ref()
const handleRow = (name, row, rowIndex) => {
  const { wr_id, pickup_type } = row
  const showLoading = () => {
    loadings[name + rowIndex] = true
  }
  const closeLoading = () => {
    loadings[name + rowIndex] = false
  }
  const handle = {
    edit: () => {
      addRef?.value.open(wr_id)
    },
    download: async () => {
      showLoading()
      await download(row.oss_url)
      closeLoading()
    },
    upload: () => {
      uploadRef?.value.open(wr_id)
    },
    change: () => {
      changeRef?.value.open({wr_id, pickup_type})
    },
    log: () => {
      logRef?.value.open({ log_type: baseName, wr_id })
    },
  }
  handle[name]()
}

// 列表配置
const totalMoney = ref({})
const tableOptions = reactive({
  rowConfig: { height: 92 },
  showHeaderOverflow: false,
  formConfig: {
    data: {
      input: { type: 'deliver_no', value: '' },
      skuInfo: { type: 'sku', value: '' },
      dateRange: { type: 'except_deliver_time', value: [], range: true },
    }
  },
  columns: [
    { type: 'checkbox', width: 40, fixed: 'left' },
    {
      width: 200, slots: {
        header: () => <div>供应商<br />供应商地址<br/>供应商ID</div>,
        default: ({ row, rowIndex }) => <VMore key={rowIndex}>
          {{
            default: (line) => row.supplier.map(d => <div class='w-full'>
              <div>{d.suppler_name}</div>
              <VText value={d.factory_address} line={line} />
              <VText>{d.suppler_code}</VText>
            </div>)
          }}
        </VMore>
      }
    },
    {
      width: 200, slots: {
        header: () => <div>头程备库单号<br />头程备库类型<br />预计出库时间</div>,
        default: ({ row }) => <div>{row.deliver_no}<br />{row.pickup_type_name}<br />{row.except_deliver_time}</div>
      }
    },
    { title: '提货类型', field: 'pickup_type_name', width: 100 },
    {
      width: 160, slots: {
        header: () => <div>采购单<br />采购人员</div>,
        default: ({ row, rowIndex }) => <VMore key={rowIndex}>
          {{
            default: (line) => (row.purchase || []).map(d => <div class='w-full'>
              <VText value={d.purchase_no} line={line} />
              <VText value={d.purchase_user_name} line={line} />
            </div>)
          }}
        </VMore>
      }
    },
    {
      width: 170, slots: {
        header: () => <div>外验完成时间</div>,
        default: ({ row }) => <VText value={row.complete_time} />
      }
    },
    {
      width: 100, slots: {
        header: () => <div>sku</div>,
        default: ({ row }) => {
          const content = row.sku.map(d => <VText value={d} />)
          return content
        }
      }
    },
    {
      title: '图片', width: 100, slots: {
        default: ({ row }) => <VImage src={row.main_img} size="80px"></VImage>
      }
    },
    {
      width: 90, slots: {
        header: () => <div>装箱信息</div>,
        default: ({ row }) => <el-button link type='primary' onClick={() => boxDetailRef?.value.open(row.deliver_no)}>装箱详情</el-button>
      }
    },
    {
      width: 120, slots: {
        header: () => <div>上传人员<br />上传时间</div>,
        default: ({ row }) => <div><VText value={row.upload_user_name} /><VText value={row.upload_time} /></div>
      }
    },
    {
      width: 120, slots: {
        header: () => <div>入仓单文件</div>,
        default: ({ row }) => {
          const {receipt_file} = row
          if(!receipt_file?.length) return '-'
          return receipt_file.map(d => <a href={d} target="_blank" download={d}><VText value={d} line={2} type='link' /></a>)
        }
      }
    },
    {
      width: 120, slots: {
        header: () => <div>备注</div>,
        default: ({ row }) => <VText value={row.remark} line={3} />
      }
    },
    {
      width: 180, slots: {
        header: () => <div>跟踪信息</div>,
        default: ({ row }) => <div>
          <VText title='司机'>{row.driver_name}</VText>
          <VText title='电话'>{row.phone}</VText>
          <VText title='车牌号'>{row.car_license}</VText>
          <VText title='柜号/so'>{row.cabinet_number}</VText>
        </div>
      }
    },
    { title: '下载次数', field: 'download_num', width: 80 },
    {
      width: 80, slots: {
        header: () => <div>签收单</div>,
        default: ({ row }) => <VImage src={row.sign_file} size='60px' />
      }
    },
    { title: '状态', field: 'receipt_status_name', width: 120 },
    {
      title: '操作', width: 120, fixed: 'right', slots: {
        default: ({ row, rowIndex }) => {
          const { return_status } = row
          //	状态 1待上传入仓单 2待录入跟踪信息 3待上传签收单 4已完成
          return <div class='nm flex flex-wrap gap-x-2 gap-y-0'>
            <VButton auth="/purchase/manage/warehouse/trace" link type="primary" onClick={() => handleRow('edit', row, rowIndex)}>录入追踪信息</VButton>
            <VButton auth="/purchase/manage/warehouse/uploadSign" link type="primary" onClick={() => handleRow('upload', row, rowIndex)}>上传签收单</VButton>
            <VButton auth="/purchase/manage/warehouse/change" link type="primary" onClick={() => handleRow('change', row, rowIndex)}>变更提货类型</VButton>
            <VButton auth="/purchase/manage/warehouse/log" link type="primary" onClick={() => handleRow('log', row, rowIndex)}>日志</VButton>
          </div>
        }
      }
    },
  ],
  proxyConfig: {
    autoLoad: false,
    ajax: {
      query: ({ page, form }) => api.query({ ...form, ...page })
    }
  }
})
</script>
  